#include "cmdprocess.h"
#include <QDebug>
#include "util.h"



cmdProcess::cmdProcess( QObject *parent) : QProcess(parent)
{
    connect(this, QOverload<int, QProcess::ExitStatus>::of(&QProcess::finished), [this](int exitCode, QProcess::ExitStatus exitStatus) {
           qDebug() << this->program() << this->arguments()<<this->pid() <<" Node exited with code" << exitCode << this->errorString();

          // process->deleteLater(); // 清理资源
       });

    // 连接到 readyReadStandardOutput
        QObject::connect(this, &QProcess::readyReadStandardOutput, [&]() {
            QByteArray data = this->readAllStandardOutput();
            qInfo() << "Standard Output:" << data.trimmed();
        });
}

cmdProcess::~cmdProcess()
{
    clearCmd();
}

void cmdProcess::run(QStringList cmdList)
{
    m_cmdList = cmdList;

    for(int i = 0; i < m_cmdList.size(); i++)
    {
        QString cmd = m_cmdList[i];


        this->start(cmd);


        if (!this->waitForStarted())
        {
            emit executeFaild();

            this->deleteLater();
        }else{

            emit executeSucc();
            clearCmd();
            pidList.push_back(this->processId());
        }
    }
}

void cmdProcess::clearCmd()
{
    QVector<quint64> vecChildId;
    for(int i =0; i < pidList.size(); i++)
    {
       get_child_pids(pidList[i],vecChildId);
    }


    foreach(auto pid, vecChildId)
    {
        //qDebug() << "try to kill pid" << pid;
        kill_process(pid);
    }

    for(int i =0; i < pidList.size(); i++)
    {
       kill_process(pidList[i]);
    }
}


